<?php
use think\migration\Migrator;

class SeedExamQuestions extends Migrator
{
    public function up()
    {
        $now = time();
        $types = [
            'single' => '单选题示例',
            'multi' => '多选题示例',
            'judge' => '判断题示例',
            'blank' => '填空题示例',
            'short' => '简答题示例',
        ];

        $rows = [];
        foreach ($types as $type => $title) {
            for ($i = 1; $i <= 100; $i++) {
                $content = $title . ' ' . $i;
                $score = 2;
                $analysis = $title . ' 的参考解析。';
                $options = null;
                $answer = '';

                if ($type === 'single') {
                    $options = json_encode([
                        '选项A ' . $i,
                        '选项B ' . $i,
                        '选项C ' . $i,
                        '选项D ' . $i,
                    ], JSON_UNESCAPED_UNICODE);
                    $answer = 'A';
                } elseif ($type === 'multi') {
                    $options = json_encode([
                        '选项A ' . $i,
                        '选项B ' . $i,
                        '选项C ' . $i,
                        '选项D ' . $i,
                    ], JSON_UNESCAPED_UNICODE);
                    // example: A,B
                    $answer = 'A,B';
                } elseif ($type === 'judge') {
                    $options = json_encode(['对', '错'], JSON_UNESCAPED_UNICODE);
                    $answer = 'A';
                } elseif ($type === 'blank') {
                    $options = null;
                    $answer = '示例答案 ' . $i;
                } elseif ($type === 'short') {
                    $options = null;
                    $answer = '示例简答 ' . $i;
                }

                $rows[] = [
                    'type' => $type,
                    'content' => $content,
                    'options' => $options,
                    'answer' => $answer,
                    'score' => $score,
                    'analysis' => $analysis,
                    'create_time' => $now,
                    'update_time' => $now,
                ];
            }
        }

        if (!empty($rows)) {
            // insert in batches of 200 to avoid too large single insert
            $chunks = array_chunk($rows, 200);
            foreach ($chunks as $chunk) {
                $this->table('exam_question')->insert($chunk)->save();
            }
        }
    }

    public function down()
    {
        // delete the seeded sample questions by content prefix
        $prefixes = ['单选题示例', '多选题示例', '判断题示例', '填空题示例', '简答题示例'];
        foreach ($prefixes as $p) {
            $this->execute("DELETE FROM `exam_question` WHERE `content` LIKE '{$p}%'");
        }
    }
}
